package news.controller;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import mail.TemplateMail;
import models.News;
import models.NewsType;
import models.Subscribe;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.util.HtmlUtils;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

import dao.NewsDao;
import dao.NewsTypeDao;
import dao.SubscribeDao;

@Controller
@RequestMapping("/news")
public class NewsController {
    private java.util.logging.Logger logger;
    public void Newscontroller(){
        logger = java.util.logging.Logger.getAnonymousLogger();
    }
    @RequestMapping(value="/mailto/{newsType}", method = RequestMethod.GET)
    public String mailto(@PathVariable String newsType, HttpServletRequest request,HttpServletResponse response){
        List<String> newsTypes = new ArrayList<String>();
        newsTypes.add(newsType);
        
        List<Subscribe> subscribes = getSubscribes(newsType);
        if (subscribes.isEmpty()){
            return "succ";
        }
        
        Map<String, List<News>> newsList = getNewsList(newsTypes);
        mailSomeType(newsType, subscribes, newsList);
        return "succ";
    }
    private void mailSomeType(String newsType, List<Subscribe> subscribes, 
            Map<String, List<News>> newsList){
        List<String> mailTos = new ArrayList<String>();
        for (Subscribe subscribe : subscribes){
            if (subscribe.getNewsType().equals(newsType)){
                mailTos.add(subscribe.getUsername());
            }
        }
        if (!mailTos.isEmpty()){
            if (newsList.containsKey(newsType) && newsList.get(newsType) != null){
                try {
                    if (!newsList.get(newsType).isEmpty()){
                        NewsTypeDao ntdao = new NewsTypeDao();
                        NewsType nt = new NewsType();
                        nt.setCode(newsType);
                        List<NewsType> nts = ntdao.find(nt, null);
                        String mailTitle = "";
                        if (nts.size() == 0){
                            mailTitle = "Subscribed: " + newsType + " (PoweredBy Eason)";
                        }else{
                            mailTitle = HtmlUtils.htmlUnescape(nts.get(0).getTitle()) + "  (PoweredBy Eason)";
                        }
                        TemplateMail.send(mailTitle, mailTos, newsList.get(newsType));
                    }
                } catch (Exception e) {
                    java.util.logging.Logger.getAnonymousLogger().log(Level.INFO, e.getMessage());
                    e.printStackTrace();
                }
            }
        }
    }
    private List<Subscribe> getSubscribes(String newsType){
        List<Subscribe> subscribes = new ArrayList<Subscribe>();
        
        SubscribeDao sdao = new SubscribeDao();
        if (newsType == null || newsType.equals("")){
            subscribes = sdao.list();
        }else{
            Subscribe subscribe = new Subscribe();
            subscribe.setNewsType(newsType);
            subscribes = sdao.find(subscribe, null);
        }
        
        return subscribes;
    }
    private Map<String, List<News>> getNewsList(List<String> newsTypes){
        Map<String, List<News>> newsList = new HashMap<String, List<News>>();
        NewsDao newsDao = new NewsDao();
        
        Date today = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");//可以方便地修改日期格式
        String strToday = dateFormat.format( today ); 
        
        for (String newsType : newsTypes){
            News sc = new News();
            sc.setNewsType(newsType);
            sc.setCreateTime(strToday);
            newsList.put(newsType, newsDao.find(sc, "pos asc"));
        }
        return newsList;
    }
	@RequestMapping(value="/mailto", method = RequestMethod.GET)
	public String mailto(HttpServletRequest request,HttpServletResponse response) throws IOException, ClassNotFoundException {
	    
	    List<Subscribe> subscribes = getSubscribes(null);
	    
        List<String> newsTypes = new ArrayList<String>();
        
        for (Subscribe subscribe : subscribes){
            if (!newsTypes.contains(subscribe.getNewsType())){
                newsTypes.add(subscribe.getNewsType());
            }
        }
        
        Map<String, List<News>> newsList = getNewsList(newsTypes);
	    for (String newsType : newsTypes){
	        mailSomeType(newsType, subscribes, newsList);
	    }

		return "succ";
	}

    @RequestMapping(value="/deliver/{newsType}", method = RequestMethod.POST)
    public String deliver(@PathVariable String newsType, HttpServletRequest request,HttpServletResponse response){
        
        String strNews = request.getParameter("news");
        JsonArray news = null;
        try{
            news = (new JsonParser()).parse(strNews).getAsJsonArray();
        }catch(Exception e){
            e.printStackTrace();
            return "fail";
        }
        ArrayList<Entity> entities = new ArrayList<Entity>();
        Date today = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");//可以方便地修改日期格式
        String strToday = dateFormat.format( today ); 
                
        NewsDao newsDao = new NewsDao();
        for (int i=1; i<=news.size(); i++){
            JsonObject singleNews = (JsonObject) news.get(i);
            
            News obj = new News();
            obj.setNewsType(newsType);
            obj.setNewsTitle(singleNews.get("title").getAsString());
            obj.setNewsUrl(singleNews.get("url").getAsString());
            
            // 搜索类似的新闻
            List<News> similars = null;
            similars = newsDao.find(obj, null);
            
            // 如果找不到，才插入该数据
            if (similars == null || similars.size() == 0){
                obj.setPos(i);
                obj.setCreateTime(strToday);            
                newsDao.insert(obj);
                System.out.println("succ insert news");
            }else{
                System.out.println("ignore ...");
            }
        }
        
        DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
        System.out.println(datastore.put(entities));

        //retrun to jsp page, configurated in mvc-dispatcher-servlet.xml, view resolver
        return "succ";

    }
    @RequestMapping(value="/test", method = RequestMethod.GET)
    public String test(HttpServletRequest request,HttpServletResponse response){
        System.out.println(new Date().getHours());
        return "succ";
    }
}